package com.higold.cloud.mvp.presenter

import com.higold.cloud.base.BasePresenter
import com.higold.cloud.mvp.contract.ReportContract
import com.higold.cloud.mvp.model.ReportModel
import com.higold.cloud.net.exception.ExceptionHandle
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


/**
 *    author : lxz
 *    date   : 2019/9/4 16:19
 *    desc   :
 */
class ReportPresenter : BasePresenter<ReportContract.View>(), ReportContract.Presenter {

    private val reportModel by lazy { ReportModel() }

    override fun getUploadPic(file: String) {
        checkViewAttached()
        mRootView?.showLoading()

        val file = File(file)
        val requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file)
        val filePart = MultipartBody.Part.createFormData("file", file.name, requestFile)

        val disposable = reportModel.requestUploadPic(filePart)
                .subscribe({ uploadPic ->
                    mRootView?.setUploadPic(uploadPic)
                }, { throwable ->
                    //处理异常
                    mRootView?.showError(ExceptionHandle.handleException(throwable), ExceptionHandle.errorCode)
                })
        addSubscription(disposable)
    }

    override fun getReport(params: HashMap<String, String>) {
        checkViewAttached()
        mRootView?.showLoading()
        val disposable = reportModel.requestReport(params)
                .subscribe({ report ->
                    mRootView?.setReport(report)
                }, { throwable ->
                    //处理异常
                    mRootView?.showError(ExceptionHandle.handleException(throwable), ExceptionHandle.errorCode)
                })
        addSubscription(disposable)
    }

    override fun getDailyPostList() {
        mRootView?.showLoading()
        val disposable = reportModel.requestDailyPostList()
                .subscribe({ dailyPostList ->
                    mRootView?.setDailyPostList(dailyPostList)
                }, { throwable ->
                    //处理异常
                    mRootView?.showError(ExceptionHandle.handleException(throwable), ExceptionHandle.errorCode)
                })
        addSubscription(disposable)
    }

}